package com.dszq.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dszq.apis.article.IArticleClient;
import com.dszq.common.aliyun.GreenImageScan;
import com.dszq.common.aliyun.GreenTextScan;
import com.dszq.common.tess4j.Tess4jClient;
import com.dszq.file.service.FileStorageService;
import com.dszq.model.article.dtos.ArticleDto;
import com.dszq.model.common.dtos.ResponseResult;
import com.dszq.model.common.enums.AppHttpCodeEnum;
import com.dszq.model.wemedia.pojos.WmChannel;
import com.dszq.model.wemedia.pojos.WmNews;
import com.dszq.model.wemedia.pojos.WmSensitive;
import com.dszq.model.wemedia.pojos.WmUser;
import com.dszq.utils.common.SensitiveWordUtil;
import com.dszq.wemedia.mapper.WmChannelMapper;
import com.dszq.wemedia.mapper.WmNewsMapper;
import com.dszq.wemedia.mapper.WmSensitiveMapper;
import com.dszq.wemedia.mapper.WmUserMapper;
import com.dszq.wemedia.service.WmChannelService;
import com.dszq.wemedia.service.WmNewsAutoScanService;
import com.hankcs.hanlp.utility.SentencesUtil;
//import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.avro.data.Json;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 自媒体文章自动审核服务实现类
 *
 * @author : [Lenovo]
 * @version : [v1.0]
 * @createTime : [2024/4/21 14:21]
 */
@Service
@Slf4j
@Transactional
@Async
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    public void autoScanNews(Integer id) {
        Thread thread = new Thread();
        try {
            thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new RuntimeException("文章审核没有找到该文章");
        }
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            // 从内容中提取纯文本内容和图片
            Map<String, Object> infos = getImagesAndText(wmNews);
            //自管理的敏感词过滤
            boolean isSensitive = handleSensitiveScan((String) infos.get("content"), wmNews);
            if(!isSensitive) return;
            // 审核文本内容 阿里云接口
            boolean textIsOk = handelScanText((String) infos.get("text"), wmNews);
            if (!textIsOk) {
                return;
            }
            // 审核图片 阿里云接口
            boolean imagesIsOk = handelScanImages((List<String>) infos.get("image"), wmNews);
            if (!imagesIsOk)
            {
                return;
            }
            // 审核成功，保存app端的相关的文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            // 回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWeNewsInfo(WmNews.Status.PUBLISHED.getCode(),"审核成功",wmNews);
        }
    }

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自管理的敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    public boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean key =true;
        //获取所有自定义敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是否包含敏感词
        Map<String,Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size()>0)
        {
            updateWeNewsInfo(WmNews.Status.FAIL.getCode(),"当前文章中存在违规内容"+map,wmNews);
            key = false;
        }
        return key;

    }

    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Qualifier("IArticleClientFallback")
    @Autowired
    private IArticleClient articleClient;

    /**
     * 保存审核通过后的文章信息到APP端
     *
     * @param wmNews 自媒体文章信息
     * @return 返回保存结果
     */
    //@GlobalTransactional
    public ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, articleDto);
        articleDto.setLayout(wmNews.getType());
        // 频道信息
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            articleDto.setChannelName(wmChannel.getName());
        }
        // 作者信息
        articleDto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            articleDto.setAuthorName(wmUser.getName());
        }
        // 设置文章id
        if (wmNews.getArticleId() != null) {
            articleDto.setId(wmNews.getArticleId());
        }
        articleDto.setCreatedTime(new Date());
        ResponseResult responseResult = articleClient.saveArticle(articleDto);
        return responseResult;
    }

    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private Tess4jClient tess4jClient;
    /**
     * 审核图片
     *
     * @param images  图片链接列表
     * @param wmNews  自媒体文章信息
     * @return 审核是否通过
     */
    public boolean handelScanImages(List<String> images, WmNews wmNews) {
        boolean key = true;
        if (images == null || images.size() == 0) {
            return key;
        }

        // 下载图片并进行去重
        List<String> imageBytesList = new ArrayList<>();
        images = images.stream().collect(Collectors.toList());
        try {
            for (String image : images) {
                byte[] imageBytes = fileStorageService.downLoadFile(image);
                //从byte[]转换为butteredImage
                ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                BufferedImage bufferedImage = ImageIO.read(inputStream);
                //识别图片的文字
                String words = tess4jClient.doOCR(bufferedImage);
                //审核是否包含自管理的敏感词
                boolean isSensitive = handleSensitiveScan(words, wmNews);
                if(!isSensitive){
                    return isSensitive;
                }
                imageBytesList.add(image);
            }
        }catch (Exception e){
            throw  new RuntimeException();
        }
        // 审核图片
        try {
            Map imageScanMap = greenImageScan.imageScan(imageBytesList);
            if (imageScanMap.get("suggestion").equals("block")) {
                key = false;
                updateWeNewsInfo(WmNews.Status.FAIL.getCode(), "文章内容存在违规信息", wmNews);
            }
            if (imageScanMap.get("suggestion").equals("review")) {
                key = false;
                updateWeNewsInfo(WmNews.Status.ADMIN_AUTH.getCode(), "文章内容需要人工检查", wmNews);
            }
        } catch (Exception e) {
            key = false;
            throw new RuntimeException(e);
        }
        return key;
    }

    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 审核纯文本内容
     *
     * @param text    文本内容
     * @param wmNews  自媒体文章信息
     * @return 审核是否通过
     */
    public boolean handelScanText(String text, WmNews wmNews) {
        boolean key = true;
        if ((wmNews.getTitle() + text).length() == 0) {
            return key;
        }
        try {
            Map map = greenTextScan.greeTextScan(wmNews.getTitle() + text);
            if (map.get("suggestion").equals("block")) {
                key = false;
                updateWeNewsInfo(WmNews.Status.FAIL.getCode(), "文章内容存在违规信息", wmNews);
            }
            if (map.get("suggestion").equals("review")) {
                key = false;
                updateWeNewsInfo(WmNews.Status.ADMIN_AUTH.getCode(), "文章内容需要人工检查", wmNews);
            }
        } catch (Exception e) {
            key = false;
            throw new RuntimeException(e);
        }
        return key;
    }

    /**
     * 更新文章状态和原因
     *
     * @param status  文章状态
     * @param reason  审核原因
     * @param wmNews  自媒体文章信息
     */
    public void updateWeNewsInfo(short status, String reason, WmNews wmNews) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从文章内容中提取文本和图片信息
     *
     * @param wmNews 自媒体文章信息
     * @return 提取的文本和图片信息
     */
    public Map<String, Object> getImagesAndText(WmNews wmNews) {
        StringBuilder texts = new StringBuilder();
        List<String> imagelist = new ArrayList<>();
        // 从文章内容中提取文本和图片
        if (StringUtils.isNotBlank(wmNews.getContent())) {
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("text")) {
                    texts.append(map.get("value"));
                }
                if (map.get("type").equals("image")) {
                    imagelist.add((String) map.get("value"));
                }
            }
        }
        // 提取文章的封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] images = wmNews.getImages().split(",");
            imagelist.addAll(Arrays.asList(images));
        }
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("text", texts.toString());
        stringObjectMap.put("image", imagelist);
        return stringObjectMap;
    }
}
